<script setup lang="ts">
import {mobileRules , passwordRules ,codeRules} from '@/utils/rules'
import {ref} from 'vue'
import {showToast , type FormInstance} from 'vant'
import {loginByPassword,sendMobileCode} from '@/services/user'
import {useMobileCode} from '@/composables'

// Store
import {useUserStore} from '@/stores'
import {useRoute , useRouter} from 'vue-router'

const mobile = ref('15244667237')
const password = ref('inthepink')
const agree = ref(false)
const isPass = ref(true)
const code = ref('')
const isShow = ref(false)


const {onSend , time , form} = useMobileCode(mobile)
const store = useUserStore()
const router = useRouter()
const route = useRoute()

// 表单提交
const onSubmit = async ()=>{
  if(!agree.value) return showToast('请勾选霸王条款')
  // 校验完毕   进行登录
  const res = await loginByPassword(mobile.value,password.value)

  store.setUser(res.data)
  // 如果有 其他的回跳地址  就退回, 没有就跳转个人中心

  router.push(route.query.returnUrl as string || '/user')
  showToast('登录成功')
}
</script>

<template>
  <div class="login-page">
    <pk-nav-bar title="来登陆呀" right-text="注册去"></pk-nav-bar>
    <!-- 头部 -->

    <div class="login-head">
      <h3>{{ isPass ? '密码登录' : '短信验证码' }}</h3>
      <a href="javascript:;" @click="isPass = !isPass">
        <span>{{ !isPass ? '密码登录' : '短信验证码' }}</span>
        <van-icon name="arrow"></van-icon>
      </a>
    </div>
    <!-- 表单 -->

    <van-form autocomplete="off" @submit="onSubmit" ref="form">
      <van-field  name="mobile" placeholder="请输入手机号" v-model="mobile" :rules="mobileRules" type="tel"></van-field>
      <van-field v-if="isPass" placeholder="请输入密码" v-model="password" :rules="passwordRules" :type="isShow ? 'text' : 'password'">

        <template #button>
          <pk-icon @click="isShow = !isShow" :name="`login-eye-${isShow ? 'on' : 'off'}`"></pk-icon>
        </template>
      </van-field>



      <van-field v-else placeholder="短信验证码" v-model="code" :rules="codeRules">
        <template #button>
          <span class="btn-send" @click="onSend">{{ time > 0 ? `${time}s后重试`  : '发送验证码'}}</span>
        </template>
      </van-field>
      <div class="pk-cell">
        <van-checkbox v-model="agree">
          <span>同意</span>
          <a href="javascript:;">《用户协议》</a>
          <span>和</span>
          <a href="javascript:;">《隐私条款》</a>
        </van-checkbox>
      </div>

      <div class="pk-cell">
        <van-button block round type="primary" native-type="submit">登  陆</van-button>
      </div>

      <div class="pk-cell">
        <a href="javascript:;">忘记密码</a>
      </div>
    </van-form>

    <!-- 底部 -->
    <div class="login-footer">
      <van-divider>微信登陆</van-divider>
      <div class="icon">
        <img src="@/assets/wechat.svg" alt="">
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
  @import '@/styles/login.scss';
</style>
